﻿using AutoMapper;
using B.S.BaseData.Domain.Base;
using B.S.BaseData.Domain.Interfaces;
using B.S.BaseData.Domain.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.ReadAPI.Applications.Commands.Departments;
using MediatR;

namespace B.S.BaseData.ReadAPI.Applications.CommandHandler.Departments
{
	public class GetDepartmentMenuItemCommandHandler : IRequestHandler<GetDepartmentMenuItemCommand, ApiResult<List<MenuItem>>>
	{
		IBaseRepository<Department> depRep;
		IBaseRepository<UserInfo> userRep;
		IGetDepartUserCount getDepartUserCount;
		IMapper  mapper;


		public GetDepartmentMenuItemCommandHandler(IBaseRepository<Department> depRep, IMapper mapper, IGetDepartUserCount getDepartUserCount, IBaseRepository<UserInfo> userRep)
		{
			this.depRep = depRep;
			this.mapper = mapper;
			this.getDepartUserCount = getDepartUserCount;
			this.userRep = userRep;
		}

		public async Task<ApiResult<List<MenuItem>>> Handle(GetDepartmentMenuItemCommand request, CancellationToken cancellationToken)
		{
			try
			{
				var result=await GetMnueItem(0);
				return ApiResult<List<MenuItem>>.Success(result, StatusCodeEnum.Ok);
			}
			catch (Exception)
			{

				throw;
			}
		}

		public async Task<List<MenuItem>> GetMnueItem(int parentId)
		{
			try
			{
				var departs = depRep.GetAllAsync(a => a.ParentId == parentId).ToList();
				List<MenuItem> result=new List<MenuItem>();
				foreach (var item in departs)
				{
					result.Add(new MenuItem
					{
						value = item.DepartmentId,
						label = item.DepartmentName,
						children = await GetMnueItem(item.DepartmentId)
					});
				}
				return result;
			}
			catch (Exception)
			{

				throw;
			}
		}
	}
}
